package wangxiaotao.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import wangxiaotao.entity.alipay.AlipayQuery;
import wangxiaotao.entity.alipay.AlipayTradeQueryResponse;
import wangxiaotao.entity.alipay.PayOrderRequest;
import wangxiaotao.enums.TradeStatus;
import wangxiaotao.service.PaySocketService;
import wangxiaotao.service.TaskService;
import wangxiaotao.task.ScheduledTask;
import wangxiaotao.tool.AliPayTool;

import java.util.Map;
import java.util.Objects;

/**
 * 订单状态查询
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PayOrderTask implements TaskService {
    private final ScheduledTask scheduledTask;
    private final PaySocketService paySocketService;

    /**
     * 订单状态轮询
     * @param properties
     */
    @Override
    public void HandlerJob(Map<String,Object> properties) {
        //订单参数封装获取
        PayOrderRequest payOrderRequest = new PayOrderRequest();
        payOrderRequest.setOut_trade_no((String) properties.get("out_trade_no"));
        try {
            //向支付宝发生查询订单状态的请求
            String query = AliPayTool.query(payOrderRequest);
            //状态返回数据处理
            String res = sendMessageToSocket(query);
            //向前端发送返回的数据
            paySocketService.SendMessage((String) properties.get("userId"),res);
            //支付成功，关闭轮询订单状态
            if (Objects.equals(res, TradeStatus.TRADE_SUCCESS.getMessage())){
                scheduledTask.stop(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Integer jobId() {
        return 1;
    }

    /**
     * 根据订单的状态返回信息
     * @param query
     * @return
     */
    public String sendMessageToSocket(String query){
        //对象封装
        AlipayTradeQueryResponse response = JSON.parseObject(query, AlipayQuery.class).getAlipay_trade_query_response();
        switch (response.getCode()){
            case 10000: break;
//            case 20000: return "";
//            case 40000: return "";
//            case 40001: return "";
//            case 40002: return "";
//            case 40003: return "";
            case 40004: return "请扫码支付";
            default: return "其他错误";
        }
        //扫码成功后状态检测
        String trade_status = response.getTrade_status();
        return TradeStatus.valueOf(trade_status).getMessage();
    }
}
